1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
|
import CredentialsProvider from "next-auth/providers/credentials"
import { getOrCreateSAMLUser, validateSAMLUserData } from '@/lib/users/saml-service'
import { encode } from 'next-auth/jwt'
import type { User } from 'next-auth'
import type { SAMLUser } from './utils'
import { debugLog, debugError, debugSuccess, debugProcess } from '@/lib/debug-utils'
interface SAMLProviderOptions {
id: string
name: string
idp: {
sso_login_url: string
sso_logout_url: string
certificates: string[]
}
sp: {
entity_id: string
private_key: string
certificate: string
assert_endpoint: string
}
}
export function SAMLProvider(options: SAMLProviderOptions) {
return CredentialsProvider({
id: options.id,
name: options.name,
credentials: {
user: {
label: "User Data",
type: "text"
}
},
async authorize(credentials) {
debugLog('🔍 SAMLProvider.authorize called with credentials:', credentials);
try {
debugLog('🔍 Checking credentials.user:', {
hasCredentials: !!credentials,
hasUser: !!credentials?.user,
userType: typeof credentials?.user,
userValue: credentials?.user?.substring?.(0, 100) + '...'
});
if (!credentials?.user) {
debugError('No user data provided in credentials')
return null
}
debugProcess('SAML Provider: Processing user data')
// 사용자 데이터 파싱 (UTF-8 처리 개선)
const userDataString = credentials.user
debugLog('🔤 Raw user data string:', userDataString.substring(0, 200) + '...')
let userData;
try {
userData = JSON.parse(userDataString);
debugSuccess('JSON parsing successful:', userData);
} catch (parseError) {
debugError('JSON parsing failed:', parseError);
debugError('Raw string that failed to parse:', userDataString);
return null;
}
// 파싱된 데이터의 UTF-8 확인
debugLog('🔤 Parsed user data UTF-8 check:', {
name: userData.name,
nameLength: userData.name?.length,
charCodes: userData.name ? [...userData.name].map(c => c.charCodeAt(0)) : []
})
if (!userData.id || !userData.email) {
debugError('Invalid SAML user data:', userData)
return null
}
debugSuccess('SAML Provider: User authenticated successfully', {
id: userData.id,
email: userData.email,
name: userData.name
})
// 🔥 SAML 사용자 데이터 검증
debugProcess('Validating SAML user data structure...');
const isValidData = await validateSAMLUserData(userData)
debugLog('Validation result:', isValidData);
if (!isValidData) {
debugError('Invalid SAML user data structure:', userData)
return null
}
// 🔥 JIT (Just-In-Time) 사용자 생성 또는 조회
debugProcess('Creating/getting SAML user from database...');
const userCreateData = {
email: userData.email,
name: userData.name,
companyId: undefined,
techCompanyId: undefined,
domain: userData.domain
};
debugLog('User create data:', userCreateData);
const dbUser = await getOrCreateSAMLUser(userCreateData)
debugLog('Database user result:', dbUser);
if (!dbUser) {
debugError('Failed to get or create SAML user')
return null
}
// DB에서 가져온 실제 사용자 정보 반환
const userResult = {
id: String(dbUser.id), // DB의 실제 ID
name: dbUser.name, // DB의 실제 이름
email: dbUser.email, // DB의 실제 이메일
companyId: dbUser.companyId, // DB의 실제 회사 ID
techCompanyId: dbUser.techCompanyId, // DB의 실제 기술회사 ID
domain: dbUser.domain, // DB의 실제 도메인
imageUrl: dbUser.imageUrl, // DB의 실제 이미지 URL
}
debugSuccess('SAML Provider: Returning user data to NextAuth:', userResult)
return userResult
} catch (error) {
debugError('SAML Provider: Authentication failed', {
error: error instanceof Error ? error.message : String(error),
stack: error instanceof Error ? error.stack : undefined,
errorType: typeof error,
credentials: credentials
});
return null
}
}
})
}
// SAML 로그인 URL 생성 헬퍼 함수
export function getSAMLLoginUrl(options: SAMLProviderOptions): string {
const params = new URLSearchParams({
SAMLRequest: 'placeholder', // 실제로는 createAuthnRequest()로 생성
RelayState: options.sp.assert_endpoint,
})
return `${options.idp.sso_login_url}?${params.toString()}`
}
// SAML 설정 검증
export function validateSAMLOptions(options: SAMLProviderOptions): boolean {
const required = [
options.idp.sso_login_url,
options.sp.entity_id,
options.sp.assert_endpoint
]
return required.every(field => field && field.length > 0)
}
// SAMLProvider의 authorize 함수를 직접 호출하기 위한 헬퍼
export async function authenticateSAMLUser(userData: SAMLUser) {
debugLog('authenticateSAMLUser called with:', userData);
try {
// SAMLProvider 대신 직접 로직 실행 (Provider 래퍼 없이)
debugProcess('SAML User Authentication: Processing user data')
// 사용자 데이터 검증
if (!userData.id || !userData.email) {
debugError('Invalid SAML user data:', userData)
return null
}
debugSuccess('SAML User data validated successfully', {
id: userData.id,
email: userData.email,
name: userData.name
})
// 🔥 SAML 사용자 데이터 검증
debugLog('Validating SAML user data structure...');
const isValidData = await validateSAMLUserData(userData)
debugLog('Validation result:', isValidData);
if (!isValidData) {
debugError('Invalid SAML user data structure:', userData)
return null
}
// 🔥 JIT (Just-In-Time) 사용자 생성 또는 조회
debugLog('Creating/getting SAML user from database...');
const userCreateData = {
email: userData.email,
name: userData.name,
companyId: undefined,
techCompanyId: undefined,
domain: userData.domain
};
debugLog('User create data:', userCreateData);
const dbUser = await getOrCreateSAMLUser(userCreateData)
debugLog('Database user result:', dbUser);
if (!dbUser) {
debugError('Failed to get or create SAML user')
return null
}
// DB에서 가져온 실제 사용자 정보 반환
const userResult = {
id: String(dbUser.id), // DB의 실제 ID
name: dbUser.name, // DB의 실제 이름
email: dbUser.email, // DB의 실제 이메일
companyId: dbUser.companyId, // DB의 실제 회사 ID
techCompanyId: dbUser.techCompanyId, // DB의 실제 기술회사 ID
domain: dbUser.domain, // DB의 실제 도메인
imageUrl: dbUser.imageUrl, // DB의 실제 이미지 URL
}
debugSuccess('SAML User Authentication completed:', userResult)
return userResult;
} catch (error) {
debugError('authenticateSAMLUser error:', {
error: error instanceof Error ? error.message : String(error),
stack: error instanceof Error ? error.stack : undefined,
userData
});
return null;
}
}
// TODO: SecuritySetting 함수에서 가져올 것
// NextAuth JWT 토큰 생성 헬퍼
export async function createNextAuthToken(user: User): Promise<string> {
const token = {
id: user.id,
email: user.email,
name: user.name,
companyId: user.companyId,
techCompanyId: user.techCompanyId,
domain: user.domain,
imageUrl: user.imageUrl,
iat: Math.floor(Date.now() / 1000),
exp: Math.floor(Date.now() / 1000) + (480 * 60) // 480분
};
const secret = process.env.NEXTAUTH_SECRET!;
return await encode({ token, secret });
}
// NextAuth 세션 쿠키 이름 가져오기
export function getSessionCookieName(): string {
// NEXTAUTH_URL이 HTTPS인 경우에만 __Secure- 접두사 사용
const nextAuthUrl = process.env.NEXTAUTH_URL || '';
const isHttps = nextAuthUrl.startsWith('https://');
return isHttps
? '__Secure-next-auth.session-token'
: 'next-auth.session-token';
}
|